#include <iostream>
#include <sys/types.h>          
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <pthread.h>
#include <string.h>
#include "Terminal.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n" << endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void* recv_message(void* args)
{
    cout << "Start OpenTerminal" << endl;

    //OpenTerminal();

    cerr << "OpenTerminal Sucess ..." << endl;

    ThreadData *td = static_cast<ThreadData*>(args);

    char buffer[1024] = {0};
    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(td->sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&temp,&len);

        //cout << "recvfrom success, data is : " << buffer << endl;

        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}

void* send_message(void* args)
{
    ThreadData *td = static_cast<ThreadData*>(args);

    string message;
    socklen_t len = sizeof(td->server);

    std::string welcome = td->serverip;
    welcome += "comming...";
    sendto(td->sockfd,welcome.c_str(),welcome.size(),0,(const sockaddr *)&(td->server),len);

    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin,message);

        //1. 数据 2. 给谁发

        sendto(td->sockfd,message.c_str(),message.size(),0,(const sockaddr *)&(td->server),len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    ThreadData td;

   
    bzero(&td.server,sizeof(td.server));

    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET,SOCK_DGRAM,0);
    td.serverip = serverip;

    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    //client需要bind吗?要! 只不过不需要用户显示的bind! 一般由OS自由随机选择!
    //一个端口号只能被一个进程bind, 对server是如此, 对于client, 也是如此!
    //其实client的port是多少,其实不重要, 只要保证主机上的唯一性就可以!

    pthread_t recvr,sender;

    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);

    close(td.sockfd);

    return 0;
}
